import fetch from 'common/src/utils/fetch';
import Cookies from 'js-cookie';
import utils from 'common/src/utils/utils';

function cacheSessionData(res) {
    if (res.code == 200) {
        // save session data to localStorage
        localStorage.setItem('sessiondata', JSON.stringify(res.data));
    }
}

function clearCache() {
    localStorage.removeItem('sessiondata');
}

export function getSessionData(data) {
    return fetch({
        url: '/api/sessionservice/session/login',
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        data
    }).then(res => {
        cacheSessionData(res);
        return res;
    });
}

export function getSessionDataByLocal(data) {
    return fetch({
        url: '/api/sessionservice/session/localLogin',
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        data
    }).then(res => {
        cacheSessionData(res);
        return res;
    });
}

export function logout(data) {
    return fetch({
        url: '/api/sessionservice/session/logout',
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        data
    }).then(res => {
        if (res.code == 200) {
            Cookies.remove('sessionid');
        }
        return res;
    });
}

export function setLanguage(data) {
    return fetch({
        url: '/api/sessionservice/session/setLanguage',
        method: 'put',
        headers: {
            'Content-Type': 'application/json'
        },
        data
    });
}

/**
 * mock指定学生或老师
 * @param {data} data
 */
export function mock(data) {
    return fetch({
        url: '/api/sessionservice/session/mock',
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        data
    }).then(res => {
        cacheSessionData(res);
        return res;
    });
}

/**
 * 退出mock模式还原用户信息
 * @param {data} data
 */
export function mockOff(data) {
    return fetch({
        url: '/api/sessionservice/session/mockOff',
        method: 'put'
    }).then(res => {
        if (res.code == 200) {
            clearCache();
        }
        return res;
    });
}

/**
 * 获取当前用户信息
 * @param {data} data
 */
export function getSessionUserNoCache() {
        return fetch({
            url: '/api/sessionservice/session/getSessionUser',
            method: 'GET'
        }).then(res => {
            return res;
        });
}

/**
 * 获取当前用户信息, 优先查询缓存
 * @param {data} data
 */
export function getSessionUser() {
    var sessiondata = localStorage.getItem('sessiondata');
    if (sessiondata) {
        return new Promise((resolve, reject) => {
            resolve({ code: 200, data: JSON.parse(sessiondata) });
        });
    } else {
        return fetch({
            url: '/api/sessionservice/session/getSessionUser',
            method: 'GET'
        }).then(res => {
            cacheSessionData(res);
            return res;
        });
    }
}

export function pingSession() {
    return fetch({
        url: '/api/sessionservice/session/ping',
        method: 'GET'
    });
}
// 切换管理部门
export function updateCurrentManageDptId(id = '') {
    return fetch({
        url: `/api/sessionservice/session/getSessionByCurrentManageDptId?currentManageDptId=${id}`,
        method: 'get'
    }).then(res => {
        cacheSessionData(res);
        return res;
    });
}
// 选择身份
export function toggleCurrentUserRole(data = {}) {
    return fetch({
        url: `/api/sessionservice/session/getSessionByCurrentRole?currentRole=${data.currentRole}&flag=${data.flag}`,
        method: 'get',
    }).then(res => {
        cacheSessionData(res);
        return res;
    });
}

export function currentAuthId(data) {
    return fetch({
        url: '/api/sessionservice/session/currentAuthId',
        method: 'post',
        data
    }).then(res => {
        return res
    })
}
export function checkVerCode(code, authId) {
    return fetch({
        url: `api/sessionservice/session/validateVerCode?verCode=${code}&authId=${authId}`,
        method: 'get',
    }).then(res => {
        return res
    })
}
function showMessageBox(message, statusCode, detail) {
    if (window.isSessionDialogOut !== true) {
        window.isSessionDialogOut = true; // 解决会弹出多个过期提示问题
        window.vueApp.showMsgBox({
            message: message || '系统故障，请联系管理员！',
            detail: detail,
            callback: ()=>{
                window.isSessionDialogOut = false;
            }
        });
    }
}
export function getSSOLogoutUrl(data) {
    return fetch({
        url: `/api/ssoservice/system/revoking?uid=${data}`,
        method: 'GET',
    }).then(resp => {
        if (resp && resp.code == 200 && resp.msg) {
            window.location.href = 'https://ids.tongji.edu.cn:8443/nidp/app/logout?url=' + resp.msg
            // let x = window.open('https://ids.tongji.edu.cn:8443/nidp/app/logout?local=true', '', 'width=100,height=100');
            // setTimeout(function(){
            //     x.close();
            //     setTimeout(() => {
            //         window.location.href = resp.msg
            //     }, 500)
            // }, 500);

        } else {
            showMessageBox('sso logout failed')
        }
    });
}